<?php
/**
 * Created by 柚子i.
 * User: Emperor
 * Date: 2019/6/25
 * Time: 11:44
 */

namespace app\api\controller;


use app\common\service\CommonService;
use app\common\service\control\ControlPlan as Control;
use app\common\service\control\ControlPlanConfirm;
use app\common\service\control\ControlPlanTrack;
use app\common\service\ControlEmissionService;
use app\common\service\EmissionService;
use app\common\service\InletFlueGasService;
use think\Db;
use think\Request;
use app\common\service\ControlService;

ini_set('max_execution_time', 0);
ini_set('memory_limit', -1);
set_time_limit(0);

class ControlDeduction extends BaseController
{
    public static $companyList = [];
    public static $stationList = [];
    public static $param = [
        "async"       => 1, //0-同步 1-异步
        "callback"    => "http://39.97.181.198/demo/control/getTsinghuaPlanCompany.php",  //异步回调地址
        "custom_data" => [
            //自定义的请求参数，处理完毕后，原样返回给异步回调地址
            "plan_number" => "", //预案唯一标识号
            "target_id"   => 1 //自定义参数
        ],
        "method"      => "常规管控V2",
    ];
    public static $standardEmission = [];

    public $drainList = [];

    /**
     * ControlDeduction constructor.
     * @param Request $request
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);

        //获取公司信息数据
        static::$companyList = db('basic_company')
            ->field(['id', 'name', 'short_name', 'industry_id', 'realtime_company'])
            ->where('delete_time', 'eq', 0)
            ->select();
        static::$companyList = array_column(static::$companyList, null, 'id');

        //标准浓度值数据
        static::$standardEmission = db('basic_emission_standards')->field(['id', 'industry_id', 'emission_so2', 'emission_nox', 'emission_tsp'])->whereIn('id', [1, 2, 10, 11])->select();
        static::$standardEmission = array_column(static::$standardEmission, null, 'industry_id');

        //排口信息数据
        $drain = db('basic_drain')->where('delete_time', 'eq', 0)->select();
        foreach ($drain as $k => $v) {
            $this->drainList[$v['company_id']][$v['name']] = $v;
        }

        //站点id对应名称
        static::$stationList = [
            1 => '长治八中',
            2 => '德盛苑',
            3 => '监测站',
            4 => '清华站',
            5 => '审计局'
        ];
    }

    /**
     * Notes :获取预案跟踪状态
     * @author lichao   2019/7/18
     */
    public function getControlTrackState()
    {
        $result = array();
        try {
            $plan_type   = $this->request->param('plan_type');
            $plan_number = $this->request->param('plan_number');

            $controlPlan = new ControlPlanTrack();
            $result      = $controlPlan->getControlTrackState($plan_type, $plan_number);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('预案状态跟踪获取成功', $result);
    }

    /**
     * Notes :修改预案状态跟踪
     * @author lichao   2019/7/18
     */
    public function updateControlTrackState()
    {
        $result = array();
        try {
            $plan_number = $this->request->param('plan_number');
            $step        = $this->request->param('step');
            $track       = $this->request->param('track');

            $controlPlan = new ControlPlanTrack();
            $result      = $controlPlan->updateControlTrackState($step, $track, $plan_number);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->result($result, 1, '预案状态修改成功');
    }

    /**
     * Notes :获取提交的方案
     * @author lichao   2019/7/15
     */
    public function getConfirmPlan()
    {
        $result = array();
        try {
            $paramArr = [
                'plan_number' => $this->request->param('plan_number'),
            ];

            $control = new Control();

            $result = $control->getControlPlanStatus($paramArr);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('确认方案获取成功', $result);
    }

    /**
     * Notes :方案总结
     * @author lichao   2019/7/4
     */
    public function getConclusionData()
    {
        $result = array();
        try {
            $paramArr = [
                'plan_number' => $this->request->param('plan_number'),
                'plan_type'   => $this->request->param('plan_type'),
                // 'plan_name'   => $this->request->param('plan_name'),
            ];

            $control = new Control();

            $result = $control->getConclusionData($paramArr);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('方案总结获取成功', $result);
    }

    /**
     * Notes :站点管控效果数据
     * @author lichao   2019/7/1
     */
    public function getControlEffect()
    {
        $result = array();
        try {
            $paramArr = [
                'plan_number' => $this->request->param('plan_number'),
                'plan_type'   => $this->request->param('plan_type'),
                // 'plan_name'   => $this->request->param('plan_name'),
            ];

            $control = new ControlPlanConfirm();

            $result = $control->getControlEffect($paramArr);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('站点管控效果数据获取成功', $result);
    }

    /**
     * Notes :获取站点6参预报值、推演值、实测值趋势图数据
     * @author lichao   2019/6/29
     */
    public function getStationTrackTrendChartData()
    {
        $result = array();
        try {
            $paramArr              = [
                'plan_number' => $this->request->param('plan_number'),
                'plan_type'   => $this->request->param('plan_type'),
                // 'plan_name'   => $this->request->param('plan_name'),
                'station_id'  => $this->request->param('station_id', 1),
                'pollutant'   => $this->request->param('pollutant', 'PM10'),
            ];
            $paramArr['pollutant'] = $paramArr['pollutant'] == 'PM2.5' ? 'pm25' : strtolower($paramArr['pollutant']);

            $control = new ControlPlanConfirm();

            $result = $control->getStationTrackTrendChartData($paramArr);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('站点管控跟踪趋势图数据获取成功', $result);
    }

    /**
     * Notes :获取站点管控跟踪数据
     * @author lichao   2019/6/29
     */
    public function getStationTrackTableData()
    {
        $result = array();
        try {
            $paramArr = [
                'plan_number' => $this->request->param('plan_number'),
                'plan_type'   => $this->request->param('plan_type'),
                // 'plan_name'   => $this->request->param('plan_name'),
            ];

            $control = new ControlPlanConfirm();

            $result = $control->getStationTrackTableData($paramArr);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('站点跟踪数据获取成功', $result);
    }

    /**
     * Notes :提交方案
     * @author lichao   2019/6/28
     */
    public function confirmPlan()
    {
        $result = array();
        try {
            $control = new ControlPlanConfirm();

            $paramArr = [
                'plan_number' => $this->request->param('plan_number'),
                'plan_name'   => $this->request->param('plan_name'),
                'explain'     => $this->request->param('explain'),
            ];

            $result = $control->confirmPlanBeLaidUp($paramArr);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->result($result, 1, '方案提交成功');
    }

    /**
     * Notes :获取站点推演趋势图数据
     * @author lichao   2019/6/25
     */
    public function getStationTrendChartData()
    {
        $result = array();
        try {
            $paramArr              = [
                'plan_number' => $this->request->param('plan_number'),
                'plan_type'   => $this->request->param('plan_type'),
                'plan_name'   => $this->request->param('plan_name'),
                'station_id'  => $this->request->param('station_id'),
                'pollutant'   => $this->request->param('pollutant'),
            ];
            $paramArr['pollutant'] = $paramArr['pollutant'] == 'PM2.5' ? 'pm25' : strtolower($paramArr['pollutant']);

            $control = new Control();

            $result = $control->getStationTrendChartData($paramArr);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('站点推演趋势图数据获取成功', $result);
    }

    /**
     * Notes :获取表格推演数据
     * @author lichao   2019/6/25
     */
    public function getReservePlanData()
    {
        $result = array();
        try {
            $paramArr = [
                'plan_number' => $this->request->param('plan_number'),
                'plan_type'   => $this->request->param('plan_type'),
                'plan_name'   => $this->request->param('plan_name'),
            ];
            $control  = new Control();

            $result = $control->getStationTableData($paramArr);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('推演数据获取成功', $result);
    }

    /**
     * Notes :获取确认预案全部方案推演数据
     * @throws \MongoDB\Driver\Exception\Exception
     * @author lichao   2019/7/16
     */
    public function getPlanSummaryAll()
    {
        $aqi = array();
        try {
            $control  = new ControlPlanConfirm();
            $paramArr = [
                'plan_number' => $this->request->param('plan_number'),
                'plan_type'   => $this->request->param('plan_type'),
            ];

            $aqi = $control->getPlanSummaryAll($paramArr);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success("获取预案确认数据成功", $aqi);
    }


    /**
     * * 第一步 - 获取贡献度分析数据
     * @param Control $control
     * @throws \MongoDB\Driver\Exception\Exception
     * @author  dutongtong   2019/6/26
     */
    public function getPollutantForecastData(Control $control)
    {
        $param      = request()->param();
        $begin      = date('Y-m-d', strtotime($param['start_time']));
        $end        = date('Y-m-d', strtotime($param['end_time']));
        $planNumber = $param['plan_number'];
        try {
            $data = $control->getForecastDataByDate($planNumber, $begin, $end);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('获取溯源预报值成功', $data);
    }

    /**
     * 第一步 - 工况分析 接口
     * @param Control $control
     * @throws \MongoDB\Driver\Exception\Exception
     * @author  dutongtong   2019/6/26
     */
    public function getIndustryMonitorAnalyse(Control $control)
    {
        $param      = request()->param();
        $planNumber = $param['plan_number'];
        $type       = $param['type'];
        try {
            $data = $control->getIndustryMonitorLastWeekRecord($planNumber, $type);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('获取成功', $data);
    }

    /**
     * @param Control $control
     * @throws \MongoDB\Driver\Exception\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author  dutongtong   2019/6/28
     */
    public function getCompanyTraceToSource(Control $control)
    {
        $param      = request()->param();
        $date       = $param['date'];
        $planNumber = $param['plan_number'];
        $data       = $control->getTraceabilityDeductionAnalyse($date, $planNumber);
        $this->success('获取成功', $data);
    }

    /**
     * @param Control $control
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function getCompanyPollutent(Control $control)
    {
        $param            = request()->param();
        $stationId        = $param['station_id'] ?? 0;  // 站点ID
        $companyId        = $param['company_id'] ?? 0;  // 企业ID
        $contribution     = $param['contribution'] ?? 0;   // 污染物
        $controlStartTime = $param['control_start_time'] ?? 0;     // 管控时间
        $controlEndTime   = $param['control_end_time'] ?? 0;       // 管控时间
        $planNumber       = $param['plan_number'] ?? 0;      // 预案编号
        $drainId          = $param['drain_id'] ?? 0;      // 排口ID
        $planId           = $param['plan_id'] ?? 0;       // 方案id
        $type             = $param['type'] ?? 0;


        $result = [];

        try {
            if ($contribution == 'AQI') {

                $emission = new ControlEmissionService();
                // 减排前
                $data      = $emission->getSingleDrainEmissionDetailsEveryHour($drainId, $planNumber, 'before');
                $list      = array_column($data, $type == 'NO2' ? 'nox_emissions' : 'so2_emissions');
                $avg       = round(array_sum($list) / count($list), 3);
                $emissions = [];
                $avgList   = [];
                foreach ($data as $d) {
                    $result['before']['date'][] = $d['publish_time'];
                    $emissions[]                = round($type == 'NO2' ? $d['nox_emissions'] : $d['so2_emissions'], 3);
                    $avgList[]                  = $avg;
                }
                $result['before']['data'][] = $emissions;
                $result['before']['data'][] = $avgList;
                // 方案
                $control = new ControlEmissionService();
                $data    = $control->getSingleDrainEmissionDetailsEveryHour($drainId, $planNumber, 'plan', $planId);
                // $data      = $emission->getSingleDrainEmissionDetailsEveryHour($drainId, $planNumber, 'control');
                $list      = array_column($data, $type == 'NO2' ? 'nox_emissions' : 'so2_emissions');
                $avg       = round(array_sum($list) / count($list), 3);
                $emissions = [];
                $avgList   = [];
                foreach ($data as $d) {
                    $result['after']['date'][] = $d['publish_time'];
                    $emissions[]               = round($type == 'NO2' ? $d['nox_emissions'] : $d['so2_emissions'], 3);
                    $avgList[]                 = $avg;
                }
                $result['after']['data'][] = $emissions;
                $result['after']['data'][] = $avgList;

            } else if ($contribution == 'PM10') {
                $controlStartTime = date('Y-m-d 00:00:00', strtotime($controlStartTime));
                $to               = date('Y-m-d 00:00:00', strtotime('+1day', strtotime($controlStartTime)));
                $controlEndTime   = date('Y-m-d 00:00:00', strtotime($controlEndTime));
                $result           = [
                    "after"  => [
                        "date" => [
                            $controlStartTime,
                            $to,
                            $controlEndTime
                        ],
                        "data" => [[], []]
                    ],
                    "before" => [
                        "date" => [
                            $controlStartTime,
                            $to,
                            $controlEndTime
                        ],
                        "data" => [[], []]
                    ]
                ];
            } else {
                $result = $control->getCompanyPollutent(
                    $stationId,
                    $companyId,
                    $planNumber,
                    $planId,
                    $contribution,
                    $controlStartTime,
                    $controlEndTime
                );
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('获取成功', $result);
    }

    /**
     * 管控预案企业清单生成
     * @param Control $control
     * @throws \MongoDB\Driver\Exception\Exception
     * @author  dutongtong   2019/7/16
     */
    public function createControlCompanyList(Control $control)
    {
        $data = [];
        //查询当天预案信息
        try {
            // $plan  = db::query('select * from control_plan_name where `plan_number` = "CZ2019-08-11 001号" order by id desc limit 0,1')[0];
            $plan  = db::query('select * from control_plan_name order by id desc limit 0,1')[0];
            $begin = date('Y-m-d', strtotime($plan['control_start_time']));
            $end   = date('Y-m-d', strtotime($plan['control_end_time']));

            $commonService       = new CommonService();
            $inletFlueGasService = new InletFlueGasService();
            //获取贡献度均值
            $firstAnalysis = $control->getForecastDataByDate($plan['plan_number'], $begin, $end, true);
            unset($firstAnalysis[0]);

            //企业运行效率列表
            $companyMonitorList = [];
            foreach ($inletFlueGasService->getAllCompanyDrainConcentrationEfficiency($plan['plan_number']) as $k => $v) {
                $companyMonitorList[$v['company_id']][] = $v;
            }
            unset($v);

            //行业运行效率列表
            $industryEfficiencyList = $inletFlueGasService->getIndustryOperatingEfficiencyAll($plan['plan_number']);
            $industryEfficiencyList = array_column($industryEfficiencyList, null, 'industry_id');

            $newData = [];
            $n       = [];
            //分别计算5个站点的贡献度
            foreach ($firstAnalysis as $stationId => $stationData) {
                $ls = [];
                foreach ($stationData as $polName => $polData) {
                    if (empty($polData)) continue;
                    foreach ($polData as $key => $val) {
                        if ($val['contribution'] == 0) continue;
                        if ($stationId != 1) {
                            // 判断 其他站点中是否有 1站点 没有的企业 , 如果有则压入
                            if (!isset($newData[$polName][$val['company_id']]) || (isset($ls[$val['company_id']]) && !isset($ls[$val['company_id']][$val['outlet']]))) {
                                $ls[$val['company_id']][$val['outlet']][] = 0;
                                $newData[$polName][$val['company_id']][]  = $val;
                            }
                        } else {
                            $newData[$polName][$val['company_id']][] = $val;
                        }
                        $n[$val['company_id']][$polName][$stationId] = $n[$val['company_id']][$polName][$stationId] ?? 0;
                        $n[$val['company_id']][$polName][$stationId] += $val['contribution'];
                    }
                }
            }
            unset($stationData);
            unset($polData);
            unset($val);

            $emissionList = [];
            // $endDay = (new ControlService())->getBeforeEndTime($plan['plan_number']);
            foreach ((new EmissionService())->getAllCompanyDrainEmissionMinToHourAvg() as $v) {
                $emissionList[$v['company_id']][] = $v;
            }
            unset($v);

            $industryList = [
                1 => '电力',
                2 => '焦化',
                3 => '钢铁',
                4 => '水泥玻璃'
            ];

            static::$param['custom_data']['plan_number'] = $plan['plan_number'];
            foreach ($n as $companyId => $val) {
                $industryId   = static::$companyList[$companyId]['industry_id'];
                $industryName = $industryList[$industryId];

                static::$param['company'][$companyId] = [
                    "company_id"    => (int)$companyId,
                    "industry_id"   => (int)$industryId,
                    "industry_name" => $industryName,
                ];

                //行业运行效率 | 行业运行浓度
                static::$param['company'][$companyId]['industry'] = [
                    "so2_average_effect" => $industryEfficiencyList[$industryId]['operating_efficiency_so2'], //so2平均运行效率(0-1)
                    "nox_average_effect" => $industryEfficiencyList[$industryId]['operating_efficiency_nox'] //nox平均运行效
                ];

                $ls = [
                    'so2_contribution',
                    'nox_contribution',
                    'pm25_contribution'
                ];

                foreach ($val as $polName => $polData) {
                    foreach ($newData[$polName][$companyId] as $k => $v) {
                        for ($ii = 0; $ii < count($ls); $ii++) {
                            if (!isset(static::$param['company'][$companyId]['drain'][$v['outlet']][$ls[$ii]])) {
                                static::$param['company'][$companyId]['drain'][$v['outlet']][$ls[$ii]] = 0;
                            }
                        }
                        $companyEffect = [];
                        if ($companyId !== 1) {
                            $companyEffect = db('company_industry_monitor_simulation_day_avg')->field([
                                'gas_volume_avg',
                            ])->where('company_id', '=', $companyId)->select();
                        } else {
                            $passThreeDay = date('Y-m-d', strtotime('-7day'));
                            $passOneDay   = date('Y-m-d', strtotime('-1day'));
                            $so2Relatime  = db::query("SELECT count(*) as count,sum(inlet_gas_volume) as inlet_gas_volume FROM `company_industry_monitor_sulfur_day` WHERE publish_time BETWEEN '{$passThreeDay}' AND '{$passOneDay}' AND company_id = {$companyId}")[0];

                            $companyEffect[0]['gas_volume_avg'] = $so2Relatime['inlet_gas_volume'] * 24;
                        }

                        $v['contribution']   = max($polData) / count($newData[$polName][$companyId]); //获取5个站点中贡献度最高的站点
                        $stationId           = array_search(max($polData), $polData);
                        $v['control_status'] = 0;                                                     //企业管控状态

                        static::$param['company'][$companyId]["company_name"] = static::$companyList[$companyId]['name'];

                        $current = &static::$param['company'][$companyId]['drain'][$v['outlet']];

                        $current["name"] = $v['outlet'];

                        //排放量
                        $current["so2_emissions"] = (float)$emissionList[$companyId][$k]['so2_emissions'] ?? 0;//so2排放量(千克);
                        $current["nox_emissions"] = (float)$emissionList[$companyId][$k]['nox_emissions'] ?? 0;//nox排放量
                        $current["tsp_emissions"] = (float)$emissionList[$companyId][$k]['tsp_emissions'] ?? 0;//tsp排放量

                        //so2标准排放量(千克)
                        $current["so2_standard_emissions"] = ((float)static::$standardEmission[$industryId]['emission_so2'] * $companyEffect[$k]['gas_volume_avg']) / 1000000;
                        //nox标准排放量
                        $current["nox_standard_emissions"] = ((float)static::$standardEmission[$industryId]['emission_nox'] * $companyEffect[$k]['gas_volume_avg']) / 1000000;
                        //tsp标准排放量
                        $current["tsp_standard_emissions"] = ((float)static::$standardEmission[$industryId]['emission_tsp'] * $companyEffect[$k]['gas_volume_avg']) / 1000000;

                        //so2当前运行效率(0-1)
                        $current["so2_current_effect"] = $companyMonitorList[$companyId][$k]['efficiency_so2'] ?? 0;
                        //nox当前运行效
                        $current["nox_current_effect"] = $companyMonitorList[$companyId][$k]['efficiency_nox'] ?? 0;
                        if ($polName == 'SO2') {
                            $current["so2_contribution"] = $commonService->contributionRound($v['contribution'] / 10000); //so2贡献度(0-1)
                            $pn                          = 'so2';
                        } elseif ($polName == 'NO2') {
                            $current["nox_contribution"] = $commonService->contributionRound($v['contribution'] / 10000);
                            $pn                          = 'nox';
                        } else {
                            $current["pm25_contribution"] = $commonService->contributionRound($v['contribution'] / 10000);
                            $pn                           = 'tsp';
                        }

                        //存储数据库数据
                        array_push($data, [
                            'type'                    => $pn == 'tsp' ? 'PM2.5' : $polName,
                            'is_realtime'             => static::$companyList[$companyId]['realtime_company'],
                            'plan_number'             => $plan['plan_number'],
                            'company_id'              => $companyId,
                            'station_id'              => $stationId,
                            'drain_id'                => $this->drainList[$companyId][$v['outlet']]['id'],
                            'drain_name'              => $v['outlet'],
                            'operation_concentration' => $companyMonitorList[$companyId][$k]['concentration_' . $pn] ?? 0,
                            'operating_efficiency'    => $companyMonitorList[$companyId][$k]['efficiency_' . $pn] ?? 0,
                            'industry_efficiency'     => static::$param['company'][$companyId]['industry'][$pn . '_average_effect'] ?? 0,
                            'contribution_degree'     => $v['contribution'] / 100,
                            'concentration'           => $v['pollutant_concentration'],
                            'industry_id'             => (int)$industryId,
                            'region_id'               => 53,
                            'create_time'             => time(),
                            'update_time'             => time(),
                            'control_status'          => 0,
                            'industry_type'           => 1,
                            'emission'                => $emissionList[$companyId][$k][$pn . '_emissions'],
                            'standard_emissions'      => $current[$pn . "_standard_emissions"],
                        ]);
                    }
                }
            }
            foreach (static::$param['company'] as &$b) {
                $b['drain'] = array_values($b['drain']);
            }

            static::$param['company']                  = array_values(static::$param['company']);
            static::$param['param']['company']         = static::$param['company'];
            static::$param['custom_data']['target_id'] = (int)$_GET['target_id'];
            static::$param['param']['target_id']       = (int)$_GET['target_id'];
            unset(static::$param['company']);

            $request = 'http://119.90.57.34:9680/channel/do';
            $res     = $this->curlRequest($request, static::$param, true);
            print_r($res);

            if (empty(db::name('control_setting_list')->where(['plan_number' => $plan['plan_number']])->find())) {
                Db::name('control_setting_list')->insertAll($data);
            }
        } catch (\Exception $e) {
            die($e->getMessage());
        }
    }

    /**
     * 发起http POST请求
     * @param      $url
     * @param null $data
     * @param bool $json
     * @return array|mixed
     */
    public function curlRequest($url, $data = NULL, $json = false)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);                     // 设置url
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);  // 验证
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 证书验证
        if (!empty($data)) {
            if ($json && is_array($data)) {
                $data = json_encode($data);
            }
            curl_setopt($curl, CURLOPT_POST, 1);            // POST请求
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);         // 发送数据
            if ($json) {            // 发送JSON数据
                curl_setopt($curl, CURLOPT_HEADER, 0);      // 设置头文件的信息作为数据流输出
                curl_setopt($curl, CURLOPT_HTTPHEADER,
                    array(
                        'Content-Type: application/json; charset=utf-8'
                    )
                );
            }
        }
        // 在尝试连接时等待的秒数
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 0);
        // 最大执行时间
        curl_setopt($curl, CURLOPT_TIMEOUT, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);      // 设置获取的信息以文件流的形式返回，而不是直接输出
        $res     = curl_exec($curl);    // 执行命令
        $errorno = curl_errno($curl);   // 返回错误
        if ($errorno) {
            return array('errorno' => false, 'errmsg' => $errorno);
        }
        curl_close($curl);              // 关闭URL请求
        return json_decode($res, true);
    }
}
